import KList from '@kernel/util/list'

/**
 * 表
 */
type TypeValue = string | number | null;
export default class KTable {
  public readonly handle: Table
  public constructor(name: string) {
    this.handle = gameapi.get_table(name)
  }

  /**
   * 长度
   */
  get size(): number {
    return <number>gameapi.get_table_length(this.handle)
  }

  /**
   * 获取值
   * @param keys
   * @param defaultValue
   */
  get<T>(keys: TypeValue[], defaultValue: T = null): T {
    return <T>gameapi.get_table_var(this.handle, keys[0], keys[1], keys[2], keys[3], keys[4], defaultValue, '')
  }

  /**
   * 遍历
   * @param keys 遍历的字段名
   * @param callback 遍历回调 返回false时结束遍历
   */
  each<T>(keys: TypeValue[], callback: (value: T) => boolean) {
    for (let i = 1; i <= this.size; i++) {
      const value: any = {}
      keys.forEach(key => {
        value[key] = this.get([i, key])
      })
      const val = callback(value)
      if (val === false) {
        break
      }
    }
  }

  /**
   * 遍历
   * @param keys 遍历的字段名
   */
  toArray<T>(keys: TypeValue[]): T[] {
    const result: T[] = []
    for (let i = 1; i <= this.size; i++) {
      const value: any = {}
      keys.forEach(key => {
        value[key] = this.get([i, key])
      })
      result.push(value)
    }
    return result
  }

  /**
   * 转列表
   * @param keys
   */
  toList<T>(keys: TypeValue[]): KList<T> {
    const result = this.toArray<T>(keys)
    const list = new KList<T>()
    result.forEach(item => list.push(item))
    return list
  }
}
